package com.xxx.system.service.impl;


import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xxx.base.exception.BusinessException;
import com.xxx.system.domain.Logininfo;
import com.xxx.system.domain.Menu;
import com.xxx.system.dto.LoginDTO;
import com.xxx.system.jwt.JwtUtil;
import com.xxx.system.jwt.Payload;
import com.xxx.system.mapper.LogininfoMapper;
import com.xxx.system.mapper.MenuMapper;
import com.xxx.system.mapper.PermissionMapper;
import com.xxx.system.query.LogininfoQuery;
import com.xxx.system.service.ILogininfoService;
import org.apache.catalina.security.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.security.Security;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类: 登录信息Logininfo
 */
@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class LogininfoServiceImpl implements ILogininfoService {

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private MenuMapper menuMapper;



    @Override
    public List<Logininfo> findAll() {
        return logininfoMapper.findAll();
    }

    @Override
    public Logininfo findOne(Long id) {
        return logininfoMapper.findOne(id);
    }

    @Override
    @Transactional
    public void delete(Long id) {
        //删除角色
        logininfoMapper.delete(id);
    }

    @Override
    @Transactional
    public void add(Logininfo logininfo) {
        //添加角色信息
        logininfoMapper.add(logininfo); //自增id
    }

    @Override
    @Transactional
    public void update(Logininfo logininfo) {
        logininfoMapper.update(logininfo);
    }

    @Override
    public void patchDelete(Long[] ids) {
       logininfoMapper.patchDelete(ids);
    }

    @Override
    public PageInfo<Logininfo> queryPage(LogininfoQuery logininfoQuery) {
        //1.开启分页
        PageHelper.startPage(logininfoQuery.getCurrentPage(),logininfoQuery.getPageSize());
        //a.查询总数量 - count()
        //b.会根据方言 mysql 自动实现分页查询,如果是mysql就会使用limit查询
        //c.自动计算limit的第一个参数: (currentPage-1)*pageSize
        //2.操作数据库
        List<Logininfo> data  = logininfoMapper.queryPage(logininfoQuery);
        return new PageInfo<>(data);
    }

    @Override
    public String login(LoginDTO loginDTO) {
        //参数校验 null  ""  "  "
        if (StrUtil.isBlank(loginDTO.getAccount())
                || StrUtil.isBlank(loginDTO.getPassword())
                || loginDTO.getType() == null){
            throw new BusinessException("参数不能为空");
        }

        //根据username和type查询tb_logininfo
        Logininfo logininfo = logininfoMapper.findByUsernameAndType(loginDTO);
        if (logininfo == null){
            throw new BusinessException("账号不存在");
        }
        //比对密码
        String passwordFromUser = SecureUtil.md5(loginDTO.getPassword() + logininfo.getSalt());
        if (!passwordFromUser.equals(logininfo.getPassword())){
            throw new BusinessException("密码错误");
        }
        //查询权限信息
        List<String> perms = permissionMapper.findPermByLogininfoId(logininfo.getId());
        //查询菜单信息
        List<Menu> menus = menuMapper.findMenusByLogininfoId(logininfo.getId());
        //将菜单信息构造成树状结构
        List<Menu> menuTree = createMenuTree(menus);

        //生成JWT字符串
        Payload payload = new Payload();
        payload.setPermissions(perms);
        payload.setMenus(menuTree);
        //登录信息脱敏
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        payload.setLogininfo(logininfo);
        String jwtToken = JwtUtil.generateToken(payload);
        return jwtToken;

    }

    private List<Menu> createMenuTree(List<Menu> all){
        // 定义返回的所有父类型集合
        List<Menu> typeTree = new ArrayList<>();

        // 将所有类型放入map集合，方便通过子类型的parentId获取父类型
        // key为id，value为类型对象(行数据)
        Map<Long, Menu> typeMap = new HashMap<>();
        for (Menu menu : all) {
            typeMap.put(menu.getId(), menu);
        }
        for (Menu menu : all) {
            // 判断父类型id是否为空
            if (menu.getParentId() == null) {
                // 父类型id为空则为父类型,将父类型放入父类型集合
                typeTree.add(menu);
            } else {
                // 否则为子类型
                // 通过子类型的父类型id从map集合拿到父类型
                Menu parent = typeMap.get(menu.getParentId());
                // 防空判断
                if (parent != null) {
                    // 拿到父类型添加子类型
                    parent.getChildren().add(menu);
                }
            }
        }
        return typeTree;
    }
}
